// 根绝用户角色权限加载动态路由

function formatRouterTree(data) {
  console.log('进来啦！！！！');
  let parents = data.filter(p => p.pid === '0'),
    children = data.filter(c => c.pid !== '0');

  dataToTree(parents, children)

  function dataToTree(parents, children) {
    parents.map(p => {
      children.map((c, i) => {

        if (c.pid === p.id) {
          let _c = JSON.parse(JSON.stringify(children));
          // 删除index=i的元素
          _c.splice(i, 1);

          dataToTree([c], _c);

          if (p.children) {
            p.children.push(c);
          } else {
            p.children = [c];
          }
        }
      })
    })
  }

  return parents
}

let rts = []
// 获取首页'/'的二级路由
function generate_Children_Routes(userRoutes) {

  userRoutes.map(r => {
    if (!r.children) {
      let rt = {
        path: r.path,
        component: () => import(`@/views/${r.viewPath}`)
      }
      if (r.redirect) {
        rt.redirect = r.redirect;
      }
      if (r.menu) {
        rt.menu = r.menu;
      }
      rt.meta = {
        title: r.title
      }
      rts.push(rt);
    } else if (r.children && r.children.length > 0) {
      generate_Children_Routes(r.children)
    }
  })
  console.log('子路由=====', rts);
}

function generateRouter(userRoutes) {
  // 所有子路由的父亲(祖先)
  const parent = userRoutes[0];
  generate_Children_Routes(parent.children)

  let route = {
    path: parent.path,
    component: () => import(`@/views/${parent.viewPath}`),
  }
  if (parent.redirect) {
    route.redirect = parent.redirect;
  }
  route.meta = {
    title: parent.title
  }
  route.children = rts;
  console.log('动态路由表：', route);
  // router.addRoutes动态添加路由规则，参数必须是一个数组，所以返回一个数组出去
  return [route];
}


export {
  formatRouterTree,
  generateRouter
}
